<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="/WEB-INF/decorators/taglibs.jsp"%>
<div class="w1a">    
<form:form modelAttribute="searchForm" id="searchForm" method="post" class="form">   
	<table width="100%" border="0" align="center" cellpadding="4" cellspacing="1" > 
		<tr><td align="center"><h2>會期維護查詢</h2></td></tr>
			<tr>
				<td align="center">會期編號：<form:input id="sessionNo" path="sessionNo" style="width:50px;"/>
				年：<form:input id="year" path="year" style="width:50px;"/>
				月：<form:input id="month" path="month" style="width:50px;"/></td>
			</tr>
			<tr>
				<td align="center">
					<a href="#do" class="easyui-linkbutton" onclick="doSearch()">查詢</a> 
					<a href="#do" class="easyui-linkbutton" onclick="fmClean()">清空</a>
				</td>
			</tr>
	</table>	
</form:form>  
<br/> 
<div>
<form:form modelAttribute="newForm" id="newForm" method="post" class="form">
	<form:input id="sessionNo" path="sessionNo" style="width:170px;" maxlength="6" class="easyui-validatebox" required="true"/>
	<form:input id="meetingDate" path="meetingDate" style="width:120px;" class="easyui-datebox"/>(yyyy/mm/dd)
	<a href="#do" class="easyui-linkbutton" onclick="save($('#newForm'))">新增</a>
	<font id="new" color="red" size="4">新增成功</font>
</form:form> 
</div>
<table id="dg" class="easyui-datagrid" style="height:360px"  url="${appPath}/session/list.json" align="center" 
	singleSelect="true" striped="true" title="會期維護" rownumbers="true" pagination="true"
	sortName="meetingDate" multiSort="true" sortable="true" sortOrder="desc"
	data-options="
		    toolbar: '#tb',
		    method: 'post',
		    onClickCell: onClickCell,
		    onAfterEdit: onAfterEdit,
		    loadFilter: loadFilter,
		    onBeforeLoad: onBeforeLoad
		     ">            
	<thead>      
    	<tr>   
            <th field="sessionNo" width="60px" sortable="true">會期</th>
            <th field="year" width="60px" sortable="true">年</th>  
            <th field="month" width="50px" sortable="true">月</th>  
            <th field="day" width="50px" sortable="true">日</th>
            <th field="meetingDate" width="120px" sortable="true" editor="datebox">日期</th>
            <th field="recorder" width="100px" formatter="recordFormat"
            	data-options="editor:{type:'combobox',
								options:{
	                            url:'${appPath}/users/findRecorder.json',
	                            method:'get',
	                            valueField:'usersSeq',
	                            textField:'name',
                            }}" 
			>記錄</th>
            <th field="action" width="450px" formatter="action">作業</th>  
		</tr>   
	</thead>   
</table> 
	<div id="tb" style="height: auto">
		<a href="javascript:void(0)" class="easyui-linkbutton"
			onclick="endEditing();">存檔</a> <a
			href="javascript:void(0)" class="easyui-linkbutton"
			onclick="callOff();">取消</a>
			<font id="hid" color="red" size="4">更新成功</font>
	</div>
</div>
<script type="text/javascript">
$.ajaxSetup ({
    cache: false,
    async:false
});
$(function() {
    $( "#hid" ).hide();
    $( "#new" ).hide();
});
function loadFilter(data) {

	var value = {
		total : data.total,
		rows : []
	};
	for (var i = 0; i < data.rows.length; i++) {
		var o = {};
		_loadArray(data.rows[i], o, "");
		value.rows.push(o);
	}
	return value;
}
function _loadArray(data, o, pre) {
	if (pre)
		pre = pre + ".";
	for ( var att in data) {
		var row = data[att];
		if (typeof (row) == "object") {
			_loadArray(row, o, pre + att);
		} else {
			if (/\d{4}-\d{2}-\d{2}/.test(row)) {
				o[pre + att] = row.replace(/\-/g, "/");
			} else {
				o[pre + att] = row;
			}
		}

	}
}

//cell edit
$.extend($.fn.datagrid.methods, {
	editCell : function(jq, param) {
		return jq.each(function() {
			var fields = $(this).datagrid('getColumnFields', true).concat(
					$(this).datagrid('getColumnFields'));
			for (var i = 0; i < fields.length; i++) {
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor1 = col.editor;
				if (fields[i] != param.field) {
					col.editor = null;
				}
			}
			$(this).datagrid('beginEdit', param.index);
			for (var i = 0; i < fields.length; i++) {
				var col = $(this).datagrid('getColumnOption', fields[i]);
				col.editor = col.editor1;
			}
		});
	}
});
function runEffect() {
    $( "#hid" ).show( "highlight", {}, 500, callback );
};
function callback() {
  setTimeout(function() {
    $( "#hid:visible" ).fadeOut();
  }, 1500 );
};
function newEffect() {
	doSearch();
	$( "form,input#sessionNo" ).val("");
	$( "form,input#meetingDate" ).datebox("setValue","");
    $( "#new" ).show( "highlight", {}, 500, function(){
    	setTimeout(function() {
    	    $( "#new:visible" ).fadeOut();
    	  }, 1500 );
    } );
};
function action(val,row,ix){ var str = "";
	var o = $('#dg').datagrid('getData').rows[ix];
	str = str.concat("[<a href='#do' onclick=\"remove(this);\">刪除</a>]");
	str = str.concat("[<a target='_p' href='${appPath}/motion/get/"+o.sessionNo+".htm'>議案基本資料</a>]");
	str = str.concat("[<a href='${appPath}/motion/choose/"+o.sessionNo+".htm'>案次決定</a>]");
	str = str.concat("[<a target='_blank' href='${appPath}/motion/decide/"+o.sessionNo+".htm'>決議內容</a>]");
	str = str.concat("[<a target='_blank' href='${appPath}/report/"+o.sessionNo+".htm'>匯出資料</a>]");
	return str; 
} 
function getRowIndex(target){
    var tr = $(target).closest("tr.datagrid-row");
    return parseInt(tr.attr("datagrid-row-index"));
}	
function remove(target){
    $.messager.confirm("Confirm","確定刪除?",function(r){
        if (r){
        	var index = getRowIndex(target);
        	var o = $("#dg").datagrid("getData").rows[index];
            $.post("${appPath}/session/delete/"+o.sessionNo+".json", 
       			function(data) {
       				if (eval(data)) {
       					$("#dg").datagrid("deleteRow", index);
       					if(editIndex>index){
       						editIndex-=1;
       					}
       				} else {
       					alert("刪除失敗!");
       				}
       				if(editIndex==index){
       					editIndex = undefined;
       				}
       		});
        }
    }); 
}
function doSearch(){ var object = {};
	$.each($('#searchForm').serializeArray(), function(i, v) { object[v.name] = v.value; });
	$('#dg').datagrid('load', object ); 
} 

function fmClean(){$("#searchForm").form('reset');}

var editIndex = undefined; // 目前編輯的row index
var editField = undefined; // 目前編輯的row index
function endEditing() {
	if (editIndex == undefined) {
		return true;
	}
	if ($("#dg").datagrid('validateRow', editIndex)) {
		$('#dg').datagrid('endEdit', editIndex);
		editIndex = undefined;
		editField = undefined;
		return true;
	} else {
		return false;
	}
}
function onClickCell(index, field) {
	if (endEditing()) {
		$('#dg').datagrid('selectRow', index).datagrid('editCell', {
			index : index,
			field : field
		});
		editIndex = index;
		editField = field;
	}
}
function onAfterEdit(index, row, changes) {
	if (Object.keys(changes).length > 0) {
		update(index);
	}
}
function onBeforeLoad(param){
	$.each($('#sessionNo').serializeArray(), function(i, v) { param[v.name] = v.value;});
}
function save( formid ){
	if( formid.form('validate') ){ 
		var o = {};
		$.each(formid.serializeArray(), function(i, v) { 
			o[v.name] = v.value; 
		});
		$.post( "${appPath}/session/save.json",o, 
			function( data ) {
				if (data=="true") {
					newEffect();
				} else if(data=="noComm"){     
					alert("新增失敗!本期委員尚未選定");
				}else{
					alert("新增失敗!");
				}
			},
			"text"
		);
	 }
	
}
function update(index) {
	var o = $("#dg").datagrid("getData").rows[index];
	$.post("${appPath}/session/update.json", o, function(data) {
		if (data == false) {
			alert("更新失敗!");
		}else{
			$("#dg").datagrid("refreshRow", index);
			$('#dg').datagrid('updateRow', {
				index : index,
				row: {
					year: data.year,
					month:data.month,
					day:data.day    
				}
			});
			runEffect();
			
		}
	});
}
function callOff() {
	$('#dg').datagrid('endEdit', editIndex);
}
function recordFormat(val,row,ix){
	var s = '';
	if(val==undefined||val == ''){
		return s;
	}
	$.ajax({
		type:"GET",
		url : "${appPath}/users/userName.json?id="+val+"&m="+Math.random(),
		async : false,
		dataType : "text",
		success : function(d) {
			s = d;
		}
	});
	return s;
}
</script>